<template>
  <div>
    <el-upload
      list-type="picture-card"
      :action="baseUrl + uploadUrl"
      :limit="limit"
      :data="theData"
      :file-list="theFileList"
      :auto-upload="autoUpload"
      :accept="accept"
      :headers="headers"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}">
        <el-image class="upload-img" fit="contain" :src="file.url" alt />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePreview(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
      <div class="el-upload__tip" slot="tip">只能上传{{accept}}文件，且不超过{{maxSize}}MB</div>
    </el-upload>
    <el-dialog :visible.sync="imageDialog" append-to-body width="80%" style="text-align: center;">
      <el-image style="max-width: 100%;" fit="contain" :src="imageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/token'
import * as auth from '@/utils/auth'
import { uuid } from '@/utils/utils'
const baseUrl = process.env.VUE_APP_BASE_API

export default {
  name: 'UploadConfigImage',
  props: {
    action: {
      type: String,
      default: ''
    },
    limit: {
      tpye: Number,
      default: 1
    },
    fileList: {
      type: Array,
      default: () => []
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.gif,.bmp'
    },
    data: {
      type: Object,
      dfeault: {}
    },
    maxSize: {
      type: Number,
      default: 5
    },
    formProp: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      baseUrl: baseUrl,
      imageDialog: false,
      imageUrl: null,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      theFileList: this.fileList,
      uploadUrl: this.action,
      theData: this.data
    }
  },
  computed: {},
  mounted() {
    this.setHeaders()
  },
  methods: {
    beforeUpload(file) {
      const filename = file.name
      const filesize = file.size
      const ext = filename.substring(filename.lastIndexOf('.'))
      if (this.accept.indexOf(ext) < 0) {
        this.$message.error('请上传' + this.accept + '格式的文件')
        return false
      }
      if (filesize > this.maxSize * 1024 * 1024) {
        this.$message.error('文件最大大小' + this.maxSize + 'MB')
        return false
      }
    },
    uploadSuccess(res, file, fileList) {
      this.$message.success('上传成功')
      if (this.formProp) {
        this.$emit('imgUploadSuccess', this.formProp, res)
      }
    },
    uploadError(error, file, fileList) {
      this.$message.error('上传失败' + error)
    },
    handlePreview(file) {
      this.imageUrl = file.url
      this.imageDialog = true
    },
    handleRemove(file) {
      this.$confirm('确认删除图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.theFileList.findIndex(fileItem => {
            return fileItem.uid === file.uid
          })
          if (index >= 0) {
            this.theFileList.splice(index, 1)
          } else {
            this.theFileList = []
          }
          if (this.formProp) {
            this.$emit('imgRemoveSuccess', this.formProp, file.type)
          }
        })
        .catch(() => {})
    },
    setHeaders() {
      this.headers['App-Auth-appid'] = auth.APPID
      if (auth.APP_AUTH_ENABLE) {
        this.headers['App-Auth-reqUrl'] = this.uploadUrl
        let timestamp = new Date().getTime()
        let nonceStr = uuid()
        this.headers['App-Auth-timestamp'] = timestamp
        this.headers['App-Auth-nonceStr'] = nonceStr
        this.headers['App-Auth-sign'] = auth.generateSignQs(
          this.uploadUrl,
          timestamp,
          nonceStr,
          {}
        )
      }
    }
  }
}
</script>

<style lang="scss">
.upload-img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
}
.el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}
.el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
  margin: 0 8px 0 0;
}
</style>
